package com.school.service;

import com.school.dao.RechargeCodeDao;
import com.school.dao.RechargeRecordDao;
import com.school.model.RechargeCode;
import com.school.model.RechargeRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class RechargeService {

    @Autowired
    private RechargeCodeDao rechargeCodeDao;

    @Autowired
    private RechargeRecordDao rechargeRecordDao;

    private static final String CHAR_POOL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    public String generateRechargeCode(int amount) {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            code.append(CHAR_POOL.charAt(random.nextInt(CHAR_POOL.length())));
            if (i % 4 == 3 && i < 15) {
                code.append("-");
            }
        }
        RechargeCode rechargeCode = new RechargeCode();
        rechargeCode.setCode(code.toString());
        rechargeCode.setAmount(amount);
        rechargeCodeDao.save(rechargeCode);
        return code.toString();
    }

    public String processRecharge(String code) {
        RechargeCode rechargeCode = rechargeCodeDao.findByCode(code);
        if (rechargeCode == null) {
            return "充值码不合规";
        }

        if (rechargeCode.isUsed()) {
            return "充值码已被使用";
        }

        rechargeCodeDao.markAsUsed(code);

        RechargeRecord record = new RechargeRecord();
        record.setRechargeCode(code);
        record.setAmount(rechargeCode.getAmount());
        record.setStatus("充值成功");
        rechargeRecordDao.save(record);
        return "充值成功，充值金额为 " + rechargeCode.getAmount();
    }

    public List<RechargeRecord> getRechargeRecords() {
        return rechargeRecordDao.findAll();
    }
}